package com.yitong.xjd.services;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yitong.base.TuiSongUtils;
import com.yitong.xjd.dao.XinJinDaiDao;
import com.yitong.xjd.domain.RequestDataWx;
import com.yitong.xjd.domain.ReturnData4Wx;
import com.yitong.xjd.domain.ZxcxData;

@Component
public class XinJinDaiScheduledTask {
	public static ObjectMapper objectMapper = new ObjectMapper();
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Value("${crm.sjyh.xjd.wxurl}")
	public String xjdWxUrl;
	@Value("${crm.sjyh.xjd.wxperson}")
	public String personStr;
	
    @Autowired
	private XinJinDaiDao xinJinDaiDao;

    
    //每天定时发送前日成功查询的征信记录
    @Scheduled(cron = "0 0 9 * * *")
    public void sendYestDayHistory() throws InterruptedException {
    	System.out.println("查询前一日成功的征信记录。。。。");
    	
		List<ZxcxData> list=xinJinDaiDao.getYestDayQueryData();
		if(list.size()>0){
			System.out.println("发送前一日成功的征信记录。。。。");
			String contentstr = getContentStr(list);
			for(String s:personStr.split("\\|")){
				postZxResultToWx(new RequestDataWx(s.split(",")[0],s.split(",")[1],"前一日成功征信数据",dateFormat.format(new Date()),contentstr), xjdWxUrl);
			}
		}
    }
    
    //每小时查询失败的的征信记录,存在则发送（获取队列中超过一个小时还没返回征信的数据）
    @Scheduled(cron = "0 */30 * * * *")
    public void sendLastHourfailureRecord() throws InterruptedException {
    	System.out.println("查询失败超过一小时的征信记录。。。。");
    	
		List<ZxcxData> list = xinJinDaiDao.getOneHourQueryData();
		
		List<ZxcxData> list1 = new ArrayList<ZxcxData>();
		for (ZxcxData node : list) {
			if (isTimeOut(node.getInputDate()))list1.add(node);
		}
		
		if(list1.size()>0){
			System.out.println("发送超过一小时失败的征信记录。。。。");
			String contentstr = getContentStr(list1);
			for(String s:personStr.split("\\|")){
				postZxResultToWx(new RequestDataWx(s.split(",")[0],s.split(",")[1], "超过时限未返回征信数据", dateFormat.format(new Date()),contentstr), xjdWxUrl);
			}
		}
    }
    
    
    
    //将列表转化为字符串
  	private String getContentStr(List<ZxcxData> list) {
  		StringBuffer content=new StringBuffer(" ");
  		for(ZxcxData node:list){
  			content.append(node.getInputDate()+" "+node.getCustName()+" "+node.getCustIdtNo()+" ").append("<br/>");
  		}
  		String contentstr=content.toString();
  		if(contentstr.endsWith("<br/>")){
  			contentstr=contentstr.substring(0, contentstr.length()-1);
  		}
  		return contentstr; 
  	}
  	
  	//判断是否超时一个小时还没返回征信
  	private boolean isTimeOut(String inputDate) {
  		try {
  			Date inputdate=dateFormat.parse(inputDate);
  			Date now=dateFormat.parse(xinJinDaiDao.getNowTime("yyyy-MM-dd hh24:mi:ss"));
  			if((now.getTime()-inputdate.getTime())>3600*1000){
  				return true;
  			}
  		} catch (ParseException e) {
  			e.printStackTrace();
  		}
  		return false;
  	}
  	
  	//推送数据给企业号
  	public ReturnData4Wx postZxResultToWx(RequestDataWx o,String url){
  		String data = null;
  		try {
  			data = objectMapper.writeValueAsString(o);
  		} catch (JsonProcessingException e) {
  			e.printStackTrace();
  			System.out.println("数据对象转换为字符串失败");
  		}
  		if(data==null||data.equals("")){
  			System.out.println("发送的报文为空");
  			return null;
  		}
  		String resultStr = null;
  		try {
  			resultStr = TuiSongUtils.tuiSong(data, url);
  		} catch (ClientProtocolException e) {
  			e.printStackTrace();
  			resultStr = null;
  		} catch (IOException e) {
  			e.printStackTrace();
  			resultStr = null;
  		}
  		if(resultStr==null||resultStr.equals("")){
  			System.out.println("返回报文为空");
  			return null;
  		}else{
  			ReturnData4Wx resultObj = null;
  			try {
  				resultObj = objectMapper.readValue(resultStr,ReturnData4Wx.class);
  			} catch (Exception e) {
  				e.printStackTrace();
  				System.out.println("返回报文格式错误"+resultObj);
  			} 
  			
  			if(resultObj!=null&&resultObj.getRetcode().equals("0")){
  				System.out.println("推送报文数据成功");
  				return resultObj;
  			}else{
  				System.out.println("推送报文数据失败");
  				return null;
  			}
  		}
  	}

}
